<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="false" @onAddData="onAddData"
          :delectData="true" @onDelectData="onDelectData"
          :optData="optText" @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <!-- <a-button type="primary" icon="vertical-align-bottom" size="small"> 自定义按钮 </a-button> -->
            <!-- <im-export></im-export> -->
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <div style="height:100%">
          <a-row style="height:100%">
            <a-col :span="tableSpan.left" style="height:100%;">
              <a-list-table
                :columns="columns"
                :tableData="listdata"
                :pagination="pagination"
                :isSelecttion="true"
                :loading="loading"
                :scroll="{y:slotData.tableHeight}"
                :changeLayout="changeLayout"
                @onTableChange="handleTableChange"
                @onselectChange="onselectChange"
                @onAction="onAction"
                :links="links"
                @onTouchlinkCell="onTouchlinkCell"
                @onTouchRow="onTouchRow"
              >
              </a-list-table>
            </a-col>
            <a-col :span="tableSpan.right" style="height:100%;border-left:1px solid #ccc;" >
              <delivery-detail :slotData="slotData" :loadDetail='loadDetail' :pid="detailPid"></delivery-detail>
            </a-col>
          </a-row>
        </div>
      </template>
    </table-layout>
     <toDeliveryModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <editOrderModal ref="editOrderModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewSaleOrderModal ref="viewSaleOrderModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import toDeliveryModal from './toDeliveryModal'
import editOrderModal from './editOrderModal'
import deliveryDetail from './deliveryDetail'
import viewSaleOrderModal from '../saleOrder/viewModal.vue'
import {
  sendOrder,
  deleteInfo,
  getByConditions,
  getByConditionsCount,
} from './saleDelivery'


const columns =[
  // {
  //   title: '配送单',
  //   children: [
      { title: '销售单号', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center',scopedSlots: { customRender: '' }},
      { title: '配送单号', dataIndex: 'deliveryOrderNo', key: 'deliveryOrderNo', align: 'center',scopedSlots: { customRender: 'deliveryOrderNo' }},
      // { title: '配送单名称', dataIndex: 'deliveryOrderName', key: 'deliveryOrderName', align: 'center'},
      // { title: '客户名称', dataIndex: 'customerName', key: 'customerName', align: 'center' },
      // { title: '送货类型', dataIndex: 'deliveryType', key: 'deliveryType', align: 'center' },
      // { title: '寄件人姓名', dataIndex: 'sender', key: 'sender', align: 'center' },
      // { title: '寄件人联系电话', dataIndex: 'senderTel', key: 'senderTel', align: 'center' },
      // { title: '收件人姓名', dataIndex: '	receiver', key: '	receiver', align: 'center' },
      // { title: '收件人联系电话', dataIndex: 'receiverTel', key: 'receiverTel', align: 'center' },
      // { title: '收件地址', dataIndex: 'receiverAddr', key: 'receiverAddr', align: 'center' },
      { title: '配送状态', dataIndex: 'deliveryState', key: 'deliveryState', align: 'center' },
      // { title: '操作', dataIndex: 'action', key: 'operation', width: 70, align: 'center', scopedSlots: { customRender: 'action' }},
  //   ]
  // }
] 
let links=['saleOrderNo','deliveryOrderNo']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    editOrderModal, 
    toDeliveryModal,
    viewSaleOrderModal,
    deliveryDetail
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      links:links,
      loading: false,
      tableSpan:{left:24,right:0},
      detailPid:'nodata',
      loadDetail:false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 1000, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        { label: '销售单号', name: 'saleOrderNo', type: 'input', placeholder: '销售单号' },
        { label: '客户名称', name: 'customerName', type: 'customer', placeholder: '客户名称' },
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        saleOrderNo: null,
        customerName: null,
        saleOrderState:'已确认'
      },
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '发货',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      changeLayout:false
    }
  },
  computed: {},
  watch: {
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
        handler: function (val, oldVal) {
          //created事件触发的函数可以在这里写... 
          console.log(this.$route); 
          if (!this.$route.meta.keepAlive) {
            if(this.$route.meta.zhuangTai){
              // this.q_formDatas.zhuangTai=this.$route.meta.zhuangTai
              this.q_formDatas.zhuangTai=null
            }
            this.getTotal()
            this.getList(this.q_formDatas)
            
          }else{//如果keepalive==true
            console.log(this.$route.params.isBack);
            if (!this.$route.params.isBack) {
              this.getTotal()
              this.getList(this.q_formDatas)
            }
            this.isJump=false
          }
          
          
        },
        deep: true,
        immediate:true
    }
  },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    // this.getTotal()
    // this.getList(this.q_formDatas)
    
  },
  methods: {
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn=['明细']
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        let haveId=resdata.find(item=>{return item.pid==this.detailPid})
        if (!haveId) {
          this.detailPid='nodata'
        }
        this.loadDetail=!this.loadDetail
        for (let item of resdata) {
          switch (item.saleOrderState) {
            case '已配送':
              actionBtn = ['明细']
              break
            default:
              actionBtn = ['明细']
          }
          listdata.push({
            key: item.pid,
            action:actionBtn,
            ...item
            })
        }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='saleOrderNo'){
        console.log(link);
        // this.$refs.viewSaleOrderModal.showModal(record.pid,record)
      }else if(link=='deliveryOrderNo'){
        this.$refs.editOrderModal.editModal(record.pid,record)
      }
    },
    onTouchRow(record, index){
      console.log(index);
      this.changeLayout=true
      this.detailPid=record.pid
      this.loadDetail=!this.loadDetail
      this.tableSpan={left:8,right:16}
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.deliveryState == '待收货') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的配送单', duration: 3 })
      }
    },
    showDelConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'配送单'+item.data.deliveryOrderNo+ '删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'配送单'+item.data.deliveryOrderNo+ '删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async delOrder(val){
      let res = await deleteInfo(val)
      return res
    },
    //发货弹框
    showConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认发货？',
        content: '发货后请提醒客户查看',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            item.deliveryState='待收货'
            reqArr.push(that.pushInfos(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1') {
                that.$message.success({ content:'已发货', duration: 3 })
              } else {
                that.$message.error({ content:'发货失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async pushInfos(val){
      let res = await sendOrder(val)
      return res
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已发货的记录，请选择未发货的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要发货的记录', duration: 3 })
      }
    }
  },
}
</script>

<style>
</style>